package com.example.administrator.im.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.VoiceRecorder;
import com.example.administrator.im.R;
import com.example.administrator.im.adapter.ChatMessageAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：wp
 * 时间：2016/4/18 13:56
 * 描述：TODO
 */
public class ChatActivity extends Activity implements EMEventListener {
    @Bind(R.id.chat_list)
    ListView chatList;
    @Bind(R.id.chat_refresh)
    SwipeRefreshLayout chatRefresh;
    @Bind(R.id.et_message)
    EditText etMessage;
    @Bind(R.id.tv_title_middle)
    TextView tvTitleMiddle;
    @Bind(R.id.tv_title_right)
    TextView tvTitleRight;
    @Bind(R.id.iv_chattingvoice_btn)
    ImageView ivChattingvoiceBtn;
    @Bind(R.id.iv_keyboard_btn)
    ImageView ivKeyboardBtn;
    @Bind(R.id.press_talk_btn)
    Button pressTalkBtn;
    @Bind(R.id.mic_image)
    ImageView micImage;
    @Bind(R.id.recording_hint)
    TextView recordingHint;
    @Bind(R.id.recording_container)
    RelativeLayout recordingContainer;
    //聊天对象
    private String username;
    private ChatMessageAdapter adapter;
    private List<EMMessage> listMsgs = new ArrayList<>();
    private AlertDialog dialog;
    //已删除
    public static final String DELETED = "deleted";
    private Drawable[] micImages;
    //录音
    private VoiceRecorder voiceRecorder;
    private Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 切换msg切换图片
            micImage.setImageDrawable(micImages[msg.what]);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);

        username = getIntent().getStringExtra("username");
        tvTitleMiddle.setText("与" + username + "聊天中");
        tvTitleRight.setVisibility(View.VISIBLE);
        tvTitleRight.setText("删除");
        EMChatManager.getInstance().getChatOptions().setRequireDeliveryAck(false);
        //如果用到已发送的回执需要把这个flag设置成
        IntentFilter deliveryAckMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction());
        deliveryAckMessageIntentFilter.setPriority(5);
        registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter);

        EMChatManager.getInstance().registerEventListener(this);
        EMChat.getInstance().setAppInited();

        adapter = new ChatMessageAdapter(this, username, listMsgs);
        chatList.setAdapter(adapter);
        adapter.refreshSelectLast();

        voiceRecorder = new VoiceRecorder(micImageHandler);
        //按住录音
        pressTalkBtn.setOnTouchListener(new PressToSpeakListen());

        // 动画资源文件,用于录制语音时
        micImages = new Drawable[]{getResources().getDrawable(R.drawable.record_animate_01),
                getResources().getDrawable(R.drawable.record_animate_02),
                getResources().getDrawable(R.drawable.record_animate_03),
                getResources().getDrawable(R.drawable.record_animate_04),
                getResources().getDrawable(R.drawable.record_animate_05),
                getResources().getDrawable(R.drawable.record_animate_06),
                getResources().getDrawable(R.drawable.record_animate_07),
                getResources().getDrawable(R.drawable.record_animate_08),
                getResources().getDrawable(R.drawable.record_animate_09),
                getResources().getDrawable(R.drawable.record_animate_10),
                getResources().getDrawable(R.drawable.record_animate_11),
                getResources().getDrawable(R.drawable.record_animate_12),
                getResources().getDrawable(R.drawable.record_animate_13),
                getResources().getDrawable(R.drawable.record_animate_14)};
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(deliveryAckMessageReceiver);
    }

    /**
     * 消息送达BroadcastReceiver
     */
    private BroadcastReceiver deliveryAckMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();

            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");
            Log.i("CHAT", msgid + "====" + from);
            EMConversation conversation = EMChatManager.getInstance().getConversation(from);
            if (conversation != null) {
                // 把message设为已读
                EMMessage msg = conversation.getMessage(msgid);
                if (msg != null) {
                    msg.isDelivered = true;
                }
            }
        }
    };

    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
            case EventNewMessage: // 接收新消息
            {
                EMMessage message = (EMMessage) event.getData();
                if (null != message)
                    adapter.refreshList();
                adapter.refreshSelectLast();
                break;
            }
            case EventDeliveryAck: {//接收已发送回执

                break;
            }

            case EventNewCMDMessage: {//接收透传消息

                break;
            }

            case EventReadAck: {//接收已读回执

                break;
            }

            case EventOfflineMessage: {//接收离线消息
                List<EMMessage> messages = (List<EMMessage>) event.getData();
                break;
            }

            case EventConversationListChanged: {//通知会话列表通知event注册（在某些特殊情况，SDK去删除会话的时候会收到回调监听）

                break;
            }

            default:
                break;
        }
    }

    /**
     * 隐藏软键盘
     */
    private InputMethodManager manager;

    private void hideKeyboard() {
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 显示选择框
     */
    private void ShowDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this).setMessage("确认删除好友吗？")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteFriends();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 取消选择框
     */
    private void hideDialog() {
        dialog.dismiss();
    }

    private void deleteFriends() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMContactManager.getInstance().deleteContact(username);//需异步处理
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.putExtra(DELETED, username);
                            ChatActivity.this.setResult(RESULT_OK, intent);
                            ChatActivity.this.finish();
                        }
                    });
                } catch (EaseMobException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    @OnClick({R.id.bt_send, R.id.iv_title_left, R.id.tv_title_right,
            R.id.iv_chattingvoice_btn, R.id.iv_keyboard_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tv_title_right:
                ShowDialog();
                break;
            case R.id.bt_send:
                sendMsg();
                break;
            case R.id.iv_chattingvoice_btn:
                ivChattingvoiceBtn.setVisibility(View.GONE);
                ivKeyboardBtn.setVisibility(View.VISIBLE);
                etMessage.setVisibility(View.GONE);
                pressTalkBtn.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_keyboard_btn:
                ivChattingvoiceBtn.setVisibility(View.VISIBLE);
                ivKeyboardBtn.setVisibility(View.GONE);
                etMessage.setVisibility(View.VISIBLE);
                pressTalkBtn.setVisibility(View.GONE);
                break;
        }

    }

    private PowerManager.WakeLock wakeLock;

    /**
     * 按住说话listener
     */
    class PressToSpeakListen implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (!isExitsSdcard()) {
                        Toast.makeText(ChatActivity.this, "录音需要SD卡", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    try {
                        v.setPressed(true);
                        recordingContainer.setVisibility(View.VISIBLE);
                        voiceRecorder.startRecording(null,username,getApplicationContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                        v.setPressed(false);
                        if(wakeLock.isHeld()) {
                            wakeLock.release();
                        }
                        if(voiceRecorder != null) {
                            voiceRecorder.discardRecording();
                        }
                        recordingContainer.setVisibility(View.INVISIBLE);
                        Toast.makeText(ChatActivity.this, "录音失败，请重新录", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    return true;
                case MotionEvent.ACTION_MOVE: {

                    return true;
                }
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if(null != wakeLock) {
                        if (wakeLock.isHeld())
                            wakeLock.release();
                    }
                    if(event.getY() < 0) {
                        voiceRecorder.discardRecording();
                    } else {
                        String st1 = "没有权限";
                        String st2 = "录音时间太短";
                        String st3 = " 发送失败，请检查网路是否正常";
                        try {
                            int length = voiceRecorder.stopRecoding();
                            if(length > 0) {
                                sendVoice(voiceRecorder.getVoiceFilePath(),voiceRecorder.getVoiceFileName(username),length,false);
                            } else if(length == EMError.INVALID_FILE) {
                                Toast.makeText(getApplicationContext(), st1, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getApplicationContext(), st2, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(ChatActivity.this, st3, Toast.LENGTH_SHORT).show();
                        }
                    }
                    return true;
                default:
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (voiceRecorder != null)
                        voiceRecorder.discardRecording();
                    return false;
            }
        }
    }

    /**
     * 发送录音
     * @param voiceFilePath
     * @param voiceFileName
     * @param length
     * @param isResend
     */
    private void sendVoice(String filePath, String voiceFileName, int length, boolean isResend) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.VOICE);
        //如果是群聊，设置chattype,默认是单聊
//        message.setChatType(EMMessage.ChatType.GroupChat);
        VoiceMessageBody body = new VoiceMessageBody(new File(filePath), length);
        message.addBody(body);
        message.setReceipt(username);
        conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError(int i, String s) {
                Log.i("VOIC", "onError" + s);
            }

            @Override
            public void onProgress(int i, String s) {
                Log.i("VOIC", "onProgress" + s);
            }
        });
        adapter.refreshList();
        adapter.refreshSelectLast();
    }

    /**
     * 检查sd卡是否存在
     *
     * @return
     */
    private boolean isExitsSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    //发送消息
    private void sendMsg() {
        String msg = etMessage.getText().toString().trim();
        if (TextUtils.isEmpty(msg)) {
            Toast.makeText(getApplicationContext(), "不能发送空消息", Toast.LENGTH_SHORT).show();
            return;
        }
        //获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid，后文中的username皆是如此
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        //创建一条文本消息
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
        //如果是群聊，设置chattype,默认是单聊
//        message.setChatType(EMMessage.ChatType.GroupChat);
        //设置消息body
        TextMessageBody txtBody = new TextMessageBody(msg);
        message.addBody(txtBody);
        //设置接收人
        message.setReceipt(username);
        //把消息加入到此会话对象中
        conversation.addMessage(message);
        //发送消息
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("CHAT", "发送消息onSuccess");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        etMessage.setText("");
                    }
                });
            }

            @Override
            public void onError(int i, String s) {
                Log.i("CHAT", "onError" + s);
            }

            @Override
            public void onProgress(int i, String s) {
                Log.i("CHAT", "onProgress" + s + i);
            }
        });
        adapter.refreshList();
        adapter.refreshSelectLast();
    }


    public ListView getListView() {
        return chatList;
    }
}
